package 剑指offer;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * 和为s的连续正数序列
 */
public class Offer57_JZ41 {
    public int[][] findContinuousSequence(int target) {
        ArrayList<int[]> res = new ArrayList<>();
        if (target == 1 || target == 2) {
            return res.toArray(new int[res.size()][]);
        }
        int i=1, j=2;
        int sum = i+j;
        int middle = (target+1) / 2;
        while (i < middle) {
            if (sum == target) {
                int[] arr1 = new int[j-i+1];
                dealData(i, j, arr1);
                res.add(arr1);
            }
            while (sum > target && i < middle) {
                sum -= i;
                i++;
                if (sum == target) {
                    int[] arr2 = new int[j-i+1];
                    dealData(i, j, arr2);
                    res.add(arr2);;
                }
            }
            j+=1;
            sum += j;
        }
        return res.toArray(new int[res.size()][]);
    }

    public void dealData(int i, int j, int[] arr) {
        for (int index=i, k=0; index<=j; index++) {
            arr[k++] = index;
        }
    }

    public static void main(String[] args) {
        Offer57_JZ41 demo = new Offer57_JZ41();
        int[][] res = demo.findContinuousSequence(9);
        System.out.println(Arrays.toString(res));
    }
}
